/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json.spi.supports;

import com.swapper.json.*;
import com.swapper.json.reflect.FieldAttributes;
import com.swapper.reflect.creator.InstanceCreator;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * common type(refers to a custom type) wrapper factory.
 */
public enum ReflectionWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    Class<?> rawType = context.getRawType(type);
    Field[] fields = rawType.getDeclaredFields();
    InstanceCreator<T> creator = context.getInstanceCreator(rawType);
    List<FieldAttributes> fieldAttributes = new ArrayList<>(fields.length);
    for (Field field : fields) {
      if ((field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) {
        fieldAttributes.add(new FieldAttributes(field, context.findWrapper(field)));
      }
    }
    return new Wrapper<>(creator, fieldAttributes);
  }

  private static final class Wrapper<T> implements JsonWrapper<T> {
    private final InstanceCreator<T> creator;
    private final Collection<FieldAttributes> fieldAttributes;

    public Wrapper(InstanceCreator<T> creator, Collection<FieldAttributes> fieldAttributes) {
      this.creator = Objects.requireNonNull(creator);
      this.fieldAttributes = Objects.requireNonNull(fieldAttributes);
    }

    @Override
    public JsonValue wrap(T value) {
      if (value == null) {
        return JsonValue.NULL;
      }
      JsonObject jsonObject = new JsonObject();
      for (FieldAttributes fieldAttributes : this.fieldAttributes) {
        if (!fieldAttributes.is_excludeSerialize()) {
          try {
            String nameOfJsonKey = fieldAttributes.nameOfMember();
            Object fieldValue = fieldAttributes.get(value);
            JsonValue jsonValue = fieldAttributes.getWrapper().wrap(fieldValue);
            jsonObject.put(nameOfJsonKey, jsonValue);
          } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
          }
        }
      }
      return jsonObject;
    }

    @Override
    public T unwrap(JsonValue value) {
      if (JsonValue.NULL.equals(value)) {
        return null;
      }
      JsonObject jsonObject = value.toJsonObject();
      T instance = creator.create();
      for (FieldAttributes fieldAttributes : this.fieldAttributes) {
        if (!fieldAttributes.is_excludeDeserialize()) {
          try {
            String nameOfMember = fieldAttributes.nameOfMember();
            JsonValue jsonValue = jsonObject.get(nameOfMember);
            if (jsonValue != null) {
              Object fieldValue = fieldAttributes.getWrapper().unwrap(jsonValue);
              fieldAttributes.set(instance, fieldValue);
            }
          } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
          }
        }
      }
      return instance;
    }
  }
}
